package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import io.appium.java_client.AppiumBy;
import io.appium.java_client.android.AndroidDriver;
import net.bytebuddy.asm.Advice.Return;
import utils.BaseAction;

public class LoginPage {

	AndroidDriver driver;
	BaseAction action;

	public LoginPage(AndroidDriver driver) {
		this.driver = driver;
		action = new BaseAction(driver);
	}

	public boolean byElementIsExist(WebElement webElement) {
		try {
			return true;
		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}
	
// 	使元素获得焦点
	public WebElement view() {
		return driver.findElement(AppiumBy.className("android.view.View"));
	}

	public WebElement edit_username() {
		return driver.findElement(AppiumBy.androidUIAutomator("new UiSelector().textContains(\"账号\")"));
	}

	public WebElement edit_password() {
		return driver.findElement(AppiumBy.androidUIAutomator("new UiSelector().textContains(\"密码\")"));
	}

	public WebElement btn_login() {
		return driver.findElement(AppiumBy.accessibilityId("登录"));
	}

//	用户名或者密码错误时：
	public WebElement fail_login() {
		return driver.findElement(AppiumBy.accessibilityId("登录失败，请检查您的成员名或密码是否填写正确。"));
	}

	public void login(String username, String password) throws InterruptedException {
		action.click(this.view());
		action.typeAndClear(this.edit_username(), username);
		action.click(this.view());
		action.typeAndClear(this.edit_password(), password);
		action.click(this.btn_login());

	}

	public HomePage loginSuccess(String username, String password) throws InterruptedException {
		login(username, password);
		return new HomePage(driver);
	}
	
//	登陆失败时，判断页面是否出现：
	public boolean loginFail(String username, String password) throws InterruptedException {
		login(username, password);
		boolean tag;
		if (byElementIsExist((this.fail_login())) == true) {
			tag = true;
		} else {
			tag = false;
		}
		return tag;
	}

}
